<template>
	<div class="quiz-container">
		<el-card v-if="!isSubmitAnswer">
			<el-text type="warning">{{(currentQuestionIndex+1)+'/'+questions.question.length}}题</el-text>
			<h2 v-if="currentQuestion.text">{{'问题' + (currentQuestionIndex + 1) + '：' + currentQuestion.text }}</h2>
			<el-radio-group v-model="selectedAnswer" v-if="currentQuestion.answers" @change="onRadioChange">
				<el-radio v-for="(answer, index) in currentQuestion.answers" :key="index" :value="answer" size="large"
					border style="margin-bottom: 10px;">
					{{ answer }}
				</el-radio>
			</el-radio-group>
			<div class="actions">
				<el-button @click="lastQuestion" type="success" :disabled="currentQuestionIndex === 0"
					plain>上一题</el-button>
				<el-button @click="submitAnswer" type="primary"
					v-show="currentQuestionIndex + 1 === questions.question.length" plain>提交答案</el-button>
				<el-button @click="nextQuestion" type="success"
					:disabled="currentQuestionIndex + 1 === questions.question.length" plain>下一题</el-button>
			</div>
		</el-card>

		<el-card v-else>
			<h2 style="color: #67C23A;">完成作答！</h2>
			<div class="result-div">
				<span class="result-span">答对：<el-text type="success"
						size="large">{{answerRightIndexArr.length}}</el-text>题</span>
				<span class="result-span">答错：<el-text type="danger"
						size="large">{{answerIndexArr.length - answerRightIndexArr.length}}</el-text>题</span>
				<span class="result-span">未答：<el-text type="warning"
						size="large">{{questions.question.length - answerIndexArr.length}}</el-text>题</span>
			</div>
			<div>
				<el-text v-if="answerRightIndexArr.length === questions.question.length && !isCompleted"
					type="primary">恭喜你！答对了全部的题，积1分！<el-icon>
						<CircleCheck />
					</el-icon></el-text>
				<el-text v-else-if="answerRightIndexArr.length === questions.question.length && isCompleted"
					type="warning">恭喜你！答对了全部的题，但是你已经完成过该单元，无法积分哦！</el-text>
				<el-text v-else type="danger">糟糕！没有答对全部的题，没有积分哦！<el-icon>
						<CircleClose />
					</el-icon></el-text>
			</div>
			<div class="result1" v-for="(question,index) in questions.question" :key="index">
				<h4>{{question.text}}</h4>
				<div>
					正确答案：
					<el-text type="info">{{question.correct}}</el-text>
				</div>
				<div>
					您的答案：
					<el-text
						:type="answerHistory[index]?answerHistory[index] === question.correct ? 'success':'danger': 'warning'">{{answerHistory[index]?answerHistory[index]:'您未作答！'}}</el-text>
				</div>
			</div>
		</el-card>
	</div>
</template>


<script setup>
	import {
		ref,
		reactive,
		computed,
		onUnmounted,
		inject
	} from 'vue';
	import {
		ElMessage
	} from 'element-plus';
	import {
		useRoute
	} from 'vue-router';
	import apiClient from '../api/index.js';

	defineOptions({
		name: 'Index'
	});

	const questions = reactive({
		question: []
	}); // 初始化为空数组

	const route = useRoute(); // 使用 useRoute 钩子
	const currentQuestionIndex = ref(0);
	const selectedAnswer = ref(null);
	const answerHistory = reactive({});
	const isSubmitAnswer = ref(false);
	const answerIndexArr = ref([]);
	const answerRightIndexArr = ref([]);
	var completedHistory = JSON.parse(localStorage.getItem('answerHistroy'));
	// 获取路由参数
	const activeId = route.query.id;

	const isCompleted = completedHistory?completedHistory.indexOf(activeId) != -1:false; 

	const globalLoading = inject('globalLoading');
	const {
		setLoading
	} = globalLoading;
	
	setLoading(true);
	if (activeId && !isNaN(activeId)) {
		apiClient.getActiveQuestion(activeId).then(res => {
			if (res.data.meta.code === 200) {
				questions.question = res.data.data.questions;
				document.title = res.data.data.activeName;
			} else {
				ElMessage({
					message: '服务器错误',
					type: 'info',
				});
				console.log(res.data.meta.msg)
			}
			setLoading(false);
		}).catch(err => {
			setLoading(false);
			ElMessage({
				message: err,
				type: 'error',
			});
			console.log(err);
		});
	}

	const currentQuestion = computed(() => {
		return questions.question.length > 0 ? questions.question[currentQuestionIndex.value] : {};
	});

	const submitAnswer = () => {
		isSubmitAnswer.value = true;
		completedHistory = completedHistory ? completedHistory : [];
		completedHistory.push(activeId);
		localStorage.setItem('answerHistroy', JSON.stringify(completedHistory));
		const isRight = answerRightIndexArr.value.length === questions.question.length;
		apiClient.uploadAnswerHistory(activeId, isRight).then(res => {
			console.log(res);
		}).then(err => {
			console.log(err);
		})
	};

	const nextQuestion = () => {
		if (currentQuestionIndex.value < questions.question.length - 1) {
			currentQuestionIndex.value++;
			selectedAnswer.value = answerHistory[currentQuestionIndex.value] ? answerHistory[currentQuestionIndex
				.value] : null;
		} else {
			ElMessage({
				message: '这是最后一题',
				type: 'info',
			});
		}
	};

	const lastQuestion = () => {
		if (currentQuestionIndex.value > 0) {
			currentQuestionIndex.value--;
			selectedAnswer.value = answerHistory[currentQuestionIndex.value] ? answerHistory[currentQuestionIndex
				.value] : null;
		} else {
			ElMessage({
				message: '这已经是第一题',
				type: 'info',
			});
		}
	};

	const onRadioChange = function(newVal) {
		answerHistory[currentQuestionIndex.value] = newVal;
		if (answerIndexArr.value.indexOf(currentQuestionIndex.value) == -1) {
			answerIndexArr.value.push(currentQuestionIndex.value);
		}
		if (answerRightIndexArr.value.indexOf(currentQuestionIndex.value) == -1 && newVal === questions.question[
				currentQuestionIndex.value].correct) {
			answerRightIndexArr.value.push(currentQuestionIndex.value);
		} else if (answerRightIndexArr.value.indexOf(currentQuestionIndex.value) != -1 && newVal !== questions
			.question[currentQuestionIndex.value].correct) {
			answerRightIndexArr.value = answerRightIndexArr.value.filter(item => item !== currentQuestionIndex.value);
		}
	}
</script>

<style scoped lang="scss">
	@keyframes shake {
		0% {
			transform: translateX(0);
		}

		25% {
			transform: translateX(-5px);
		}

		50% {
			transform: translateX(5px);
		}

		75% {
			transform: translateX(-5px);
		}

		100% {
			transform: translateX(0);
		}
	}

	@keyframes jump {
		0% {
			transform: rotate(0deg) scale(1);
		}

		25% {
			transform: rotate(-10deg) scale(1.1);
		}

		50% {
			transform: rotate(10deg) scale(1.2);
		}

		75% {
			transform: rotate(-10deg) scale(1.1);
		}

		100% {
			transform: rotate(0deg) scale(1);
		}
	}

	.shake {
		animation: shake 0.2s;
	}

	.jump {
		animation: jump 0.5s;
	}

	.quiz-container {
		max-width: 600px;
		margin: 2rem auto;
		padding: 1rem;
	}

	.actions {
		margin-top: 1rem;
		display: flex;
		justify-content: space-between;
	}

	.result-div {
		display: flex;
		justify-content: space-between;
		margin-bottom: 10px;

		.result-span {
			border: solid 1px #e7e7e7;
			border-radius: 5px;
			padding: 2px;
			box-shadow: var(--el-box-shadow-dark);
		}
	}
</style>